package com.evolved.automata.android.bots.speechbot;

public class DataDistribution 
{
	
	float[] buffer;
	
	int totalElements;
	int totalCount;
	int maxElements;
	float average;
	public DataDistribution(int capacity)
	{
		buffer = new float[capacity];
		
		this.maxElements=capacity;
	}
	
	public void reset()
	{
		totalElements=0;
		average=0;
	}
	
	public void add(float point)
	{
		if (totalElements<maxElements)
		{
			buffer[totalElements]=point;
			totalElements++;
		}
		else
		{
			shiftBackList(buffer);
			buffer[maxElements-1]=point;
		}
		average = average*totalCount/(totalCount+1)+point/(totalCount+1);
		totalCount++;
		
	}
	
	public float getLast()
	{
		return getLastNth(1);
	}
	
	/**
	 * This returns the Nth element of the buffer counted from the end.  If n = 0 then returns the last
	 * element on the buffer
	 * @param n
	 * @return
	 */
	public float getLastNth(int n)
	{
		return buffer[Math.max(0, totalElements-n)];
	}
	
	
	public float getPopulationAverage()
	{
		return average;
	}
	
	public float getSampleAverage()
	{
		return getListSum(buffer)/totalElements;
	}
	
	public float getSampleSTD()
	{
		if (totalCount<2*maxElements)
			return -1;
		float std=getSampleAverage();
		float[] stdBuffer=new float[maxElements];
		for (int i=0;i<totalElements;i++)
			stdBuffer[i]=(buffer[i]-std)*(buffer[i]-std);
		return (float)Math.sqrt(getListSum(stdBuffer)/maxElements);
		
	}
	
	
	private void shiftBackList(float[] buffer)
	{
		for (int i=1;i<buffer.length;i++)
		{
			buffer[i-1]=buffer[i];
		}
	}
	
	private float getListSum(float[] list)
	{
		float sum=0;
		for (int i=0;i<Math.min(totalElements, list.length);i++)
			sum+=list[i];
		return sum;
	}
}
